# -*- coding: utf-8 -*-
import hashlib
import json
import time
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '11198': {  # 新通宝支付 支付宝 3% 100-5000 witch
        'API_KEY': 'ftx1gac49l4otuxdt4xa64u3e85w31tzvqgrgsbq',
        'gateway': 'http://tongbao.tonghubf.com/pay/api.php',
        'query_gateway': 'http://tongbao.tonghubf.com/queryorder.php',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _get_org_no(mch_id):
    return APP_CONF[mch_id]['org_no']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(parameter, key):
    s = ''
    key_list = ['shid', 'bb', 'zftd', 'ddh', 'je', 'ddmc', 'ddbz', 'ybtz', 'tbtz']
    sorted_dict = OrderedDict((k, parameter.get(k)) for k in key_list)
    _LOGGER.info("sign sorted_dict  is: %s", sorted_dict)
    for k in sorted_dict:
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += '%s' % key
    _LOGGER.info("tongbaopay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(parameter, key):
    s = ''
    key_list = ['status', 'shid', 'bb', 'zftd', 'ddh', 'je', 'ddmc', 'ddbz', 'ybtz', 'tbtz']
    sorted_dict = OrderedDict((k, parameter.get(k)) for k in key_list)
    _LOGGER.info("notify_sign sorted_dict  is: %s", sorted_dict)
    for k in sorted_dict:
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += '%s' % key
    _LOGGER.info("tongbaopay notify_sign str: %s", s)
    return _gen_sign(s)


def generate_query_sign(parameter, key):
    s = ''
    key_list = ['out_trade_no', 'userid', 'time']
    sorted_dict = OrderedDict((k, parameter.get(k)) for k in key_list)
    _LOGGER.info("sorted_dict  is: %s", sorted_dict)
    for k in sorted_dict:
        if parameter[k]:
            s += '%s=%s&' % (k, parameter[k])
    s += 'userkey=%s' % key
    _LOGGER.info("tongbaopay query sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("tongbaopay notify sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _get_pay_type(service):
    if service == 'alipay':
        return 'alipayh5'
    return 'alipayh5'


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info['service']
    parameter_dict = OrderedDict((
        ('bb', '1.0'),
        ('shid', str(app_id)),
        ('ddh', str(pay.id)),
        ('je', '%.2f' % pay_amount),
        ('zftd', _get_pay_type(service)),
        ('bankcode', ''),
        ('ybtz', '{}/pay/api/{}/tongbaopay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('tbtz', '{}/pay/api/{}/tongbaopay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('ddmc', 'charge'),
        ('ddbz', 'tongbaopay'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    _LOGGER.info("tongbaopay create: , %s", json.dumps(parameter_dict))
    html_text = _build_form(parameter_dict, _get_gateway(app_id))
    cache_id = redis_cache.save_html(pay.id, html_text)
    _LOGGER.info('tongbaopay url: %s', settings.PAY_CACHE_URL + cache_id)
    return {'charge_info': settings.PAY_CACHE_URL + cache_id}


def check_notify_sign(request, app_id):
    data = dict(request.POST.iteritems())
    api_key = _get_api_key(app_id)
    _LOGGER.info("tongbaopay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['ddh']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('tongbaopay event does not contain pay ID')
    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)
    mch_id = pay.mch_id  # 商户编号
    trade_status = str(data['status'])
    trade_no = data['ddh']
    total_fee = float(data['je'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == 'success' and total_fee > 0.0:
        _LOGGER.info('tongbaopay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    """ 查询订单 """
    pay_id = pay_order.id
    _LOGGER.info("pay_order is: %s", pay_order)
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('userid', app_id),
        ('out_trade_no', str(pay_id)),
        ('time', int(time.time())),
    ))
    parameter_dict['sign'] = generate_query_sign(parameter_dict, api_key)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    _LOGGER.info("tongbaopay query url: %s, %s", _get_query_gateway(app_id), json.dumps(parameter_dict))
    response = requests.post(_get_query_gateway(app_id), data=parameter_dict, headers=headers, timeout=5)
    _LOGGER.info("tongbaopay query response: %s", response.text)
    if response.status_code == 200:
        data = json.loads(response.text)
        mch_id = pay_order.mch_id
        trade_status = str(data['code'])
        total_fee = float(pay_order.total_fee)
        trade_no = pay_order.id
        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }
        if trade_status == '0':
            check_channel_order(pay_id, total_fee, app_id)
            _LOGGER.info('tongbaopay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)
            async_job.notify_mch(pay_order.id)
